-module(wish_demos).

-export([start/0]).

-import(wish_lib, [cast/1, sendSock/2]).

%% create 1 window
%% monitor the process
%% when the window dies send an exit message is sent to the process
%% If we are not trapping exits (like this case) we will die

start() ->
    spawn(fun win1/0).

buttons() ->
    [{"demo1", fun() -> wish_demo1:start() end},
     {"demo2", fun wish_demo2:start/1}].

%% simplest possible window
%%   Nothing much happens

win1() ->
    %% trap exits -- now if the window dies you will not
    %% get a message
    process_flag(trap_exit, true),
    %% start wish -- you must always do this
    wish:start(),
    %% make a new window
    Win = "." ++ i2s(wish:new_index()),
    %% reserve the window. This tells ther wish server that this
    %% process is responsible for the window
    wish:reserveWin(Win),
    Buttons = buttons(),
    %% define the window geomtry
    X=100, Y=200, Width = 10, Ht = 20 + 30 * length(Buttons), Bg = "#00ff00",
    cast([toplevel,Win,{bg,Bg},{bd,1},{relief,raised}]),
    cast([bind, Win,"<Destroy>","windowDestroyed " ++ Win]),
    cast([bind, Win,"<Configure>","windowMoved " ++ Win ++ " %x %y %w %h"]),
    Desc = [i2s(Width),"x",i2s(Ht),"+",i2s(X),"+",i2s(Y)],
    %% pass means "pass the parameters unchanged"
    cast([wm,geometry,Win,{pass, Desc}]),
    %% Now go into a loop -- if the process dies the window will
    %% be destroyed.
    create_buttons(Win, Buttons, 0),
    io:format("status=~p~n",[wish:status()]),
    loop().

create_buttons(Win, [{Str,F}|T], N) ->
    Button = Win ++ "." ++ i2s(N),
    cast([button,Button, {text,Str},{command, sendSock(Button, Str)}]),
    cast([pack,Button]),
    [{Button,F}|create_buttons(Win, T, N+1)];
create_buttons(_,[],_) ->
    [].

loop() ->
    receive
	Any ->
	    io:format("process received:~p~n",[Any]),
	    loop()
    end.

    
i2s(I) -> integer_to_list(I).
		  

    
